import store from '@/store'
import config from '@/config'
import { getToken, setToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'
import { refreshToken } from '@/api/login'

let timeout = 10000
const baseUrl = config.baseUrl

// 是否正在刷新token
let isRefreshing = false
// 重试队列
let retryRequests = []

const request = config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  config.header = config.header || {}
  if (getToken() && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getToken()
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.url = url
  }
  return new Promise((resolve, reject) => {
    uni.request({
        method: config.method || 'get',
        timeout: config.timeout || timeout,
        url: config.baseUrl || baseUrl + config.url,
        data: config.data,
        header: config.header,
        dataType: 'json'
      }).then(async response => {
        let [error, res] = response
        if (error) {
          toast('后端接口连接异常')
          reject('后端接口连接异常')
          return
        }
        const code = res.data.code || 200
        const msg = errorCode[code] || res.data.msg || errorCode['default']
        
        // token过期
        if (code === 401) {
          // 如果不是刷新token的请求，则尝试刷新token
          if (!config.url.includes('/auth/refresh')) {
            if (!isRefreshing) {
              isRefreshing = true
              try {
                // 尝试刷新token
                const refreshRes = await refreshToken()
                const newToken = refreshRes.data.token
                // 更新token
                setToken(newToken)
                store.commit('SET_TOKEN', newToken)
                
                // 重试队列中的请求
                retryRequests.forEach(cb => cb(newToken))
                retryRequests = []
                
                // 重试当前请求
                config.header.Authorization = 'Bearer ' + newToken
                const retryRes = await uni.request(config)
                resolve(retryRes[1].data)
              } catch (error) {
                // 刷新token失败，清空队列
                retryRequests = []
                // 跳转到登录页
                showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(res => {
                  if (res.confirm) {
                    store.dispatch('LogOut').then(() => {
                      uni.reLaunch({ url: '/pages/login' })
                    })
                  }
                })
                reject('无效的会话，或者会话已过期，请重新登录。')
              } finally {
                isRefreshing = false
              }
            } else {
              // 将请求添加到重试队列
              return new Promise(resolve => {
                retryRequests.push(token => {
                  config.header.Authorization = 'Bearer ' + token
                  resolve(uni.request(config))
                })
              }).then(retryRes => {
                resolve(retryRes[1].data)
              })
            }
          } else {
            reject(res.data)
          }
        } else if (code === 500) {
          toast(msg)
          reject('500')
        } else if (code !== 200) {
          toast(msg)
          reject(code)
        } else {
          resolve(res.data)
        }
      })
      .catch(error => {
        console.log(error)
        let { message } = error
        if (message === 'Network Error') {
          message = '后端接口连接异常'
        } else if (message.includes('timeout')) {
          message = '系统接口请求超时'
        } else if (message.includes('Request failed with status code')) {
          message = '系统接口' + message.substr(message.length - 3) + '异常'
        }
        toast(message)
        reject(error)
      })
  })
}

export default request
